package com.ruoyi.game.core.card;

import com.ruoyi.game.core.GameSetCore;
import com.ruoyi.game.core.GameSetPos;
import com.ruoyi.game.core.GameRoundCore;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 对子牌型的出牌策略
 */
@Slf4j
public class DuiCardTypeImpl extends BaseCardType {

    @Override
    public String getName() {
        return "对子";
    }

    @Override
    public List<Integer> firstAutoOut(GameSetPos pos) {
        GameSetCore set = pos.getGameSet();
        if (set == null) {
            log.warn("[DuiCardType] 玩家 {} 首出失败，未找到所属对局", pos.getPlayerId());
            return Collections.emptyList();
        }

        int zhuColor = set.getLiangZhuInfo().getZhuColor();
        int zhuValue = set.getZhuValue();

        List<Integer> handCards = pos.getHandCards();
        List<List<Integer>> allPairs = duiList(handCards, zhuColor, zhuValue, -1);

        if (!allPairs.isEmpty()) {
            List<Integer> pair = allPairs.get(0);
            log.info("[DuiCardType] 玩家 {} 自动首出对子：{}", pos.getPlayerId(),
                    pair.stream().map(BasePoker::getCardDescription).collect(Collectors.joining(", ")));
            return pair;
        }

        log.warn("[DuiCardType] 玩家 {} 无对子可出", pos.getPlayerId());
        return Collections.emptyList();
    }


    @Override
    public List<Integer> followAutoOut(GameSetPos pos, GameRoundCore round) {
        if (round == null) {
            log.warn("[DuiCardType] 玩家 {} 跟牌失败，回合对象为空", pos.getPlayerId());
            return Collections.emptyList();
        }

        GameSetCore set = round.getRoomSet();
        int zhuColor = set.getLiangZhuInfo().getZhuColor();
        int zhuValue = set.getZhuValue();
        int firstOutColor = BasePoker.getCardColor(round.getFirstOutCards().get(0));
        List<Integer> result = findPair(pos.getHandCards(), zhuColor, zhuValue, firstOutColor);
        log.info("[DuiCardType] 玩家 {} 匹配对子：{}", pos.getPlayerId(), BasePoker.toCardString(result));
        return result;
    }


    /**
     * 从给定牌中找一个对子（花色一致），优先取最大的一组
     */
    private List<Integer> findPair(List<Integer> cards, int zhuColor, int zhuValue, int targetColor) {
        List<List<Integer>> allPairs = duiList(cards, zhuColor, zhuValue, targetColor);
        return allPairs.isEmpty() ? Collections.emptyList() : allPairs.get(0);
    }
}
